<?php

// 资讯 管理类

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Crypt;
use Session;

class NewsController extends Controller
{
    
	
	// 批量 操作 资讯审核通过
	public function passAll( Request $request )
	{
		// 包含 文章 id
		$data = $request -> except('_token');
		// 清除无效值
		unset($data['all'][0]);	
		// 1.主表
		$res = DB::table('news')
				-> whereIn( 'id',$data['all'] )
				// 3审核通过
				-> update( ['status'=>3] );
		if( !$res )
		{
			$this -> show_msg('操作失败');
		}
		$this -> show_msg('操作成功');
	
	}
	
	
	
	
	/**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
	
	// 资讯 列表
    public function index( $category_id='0', Request $request )
    {
        // 开始
        // 获取路由
        $route_array = request()->route()->getAction();
        $controller = explode("\\",$route_array['controller']);
        $result = explode("@",$controller[3]);
        // 控制器 	$result[0];
        // 方法 	$result[1];
        $auth_final = '';
        foreach( Session::get('auths') as $key=> $auth_info )
        {
            // 符合条件
            if( $auth_info['controller']==$result[0] && $auth_info['func']==$result[1] )
            {
                $auth_final = true;
                break;
            }else
            {
                $auth_final = false;
            }
        }
        // 权限验证失败
        if( !$auth_final )
        {
            return redirect('/')->with( ['authinfo'=>'没有此项权限'] );
        }
        // 结尾
		// 获取 搜索 内容
		$keyword = $request -> input('keyword',"");
		if( empty($keyword) )
		{
			// 为空 说明没有搜索
			$one = 'n.id';
			$two = '!=';
			$three = '0';
			
		}else
		{
			// 标题
			$one = 'n.title';
			$two = 'like';
			$three = '%'.$keyword.'%';
		}
		if( $category_id=='0' )
		{
			// 查询所有资讯 每页20条数据
			$news = DB::table('news as n')
					-> select( 'n.id','n.title','c.name','n.create_at',DB::raw("case when n.status=1 then '草稿' when n.status=2 then '待审核' when n.status=3 then '通过'  when n.status=4 then '已推荐' when n.status=5 then '头条'  when n.status=6 then '未通过' end as statusInfo"),'n.status','a.name as author' )
					-> leftJoin('category as c','c.id','=','n.category_id')
					-> leftJoin('admin as a','a.id','=','n.admin_id')
					-> where( $one,$two,$three ) 
					// 1草稿 2待审核 3审核通过 4推荐 5头条 6未通过
					-> orderBy('n.status','desc')
					-> orderBy('n.id','desc')
					// -> orderBy('n.create_at','desc')
					-> paginate(20);
		}else
		{
			// 查询所有资讯 每页20条数据
			$news = DB::table('news as n')
					->select( 'n.id','n.title','c.name','n.create_at',DB::raw("case when n.status=1 then '草稿' when n.status=2 then '待审核' when n.status=3 then '通过'  when n.status=4 then '已推荐' when n.status=5 then '头条'  when n.status=6 then '未通过' end as statusInfo"),'n.status','a.name as author' )
					->leftJoin('category as c','c.id','=','n.category_id')
					->leftJoin('admin as a','a.id','=','n.admin_id')
					->where( $one,$two,$three ) 
					->where( 'n.category_id','=',$category_id ) 
					// 头条3 推荐2 正常1 
					-> orderBy('n.status','desc')
					-> orderBy('n.id','desc')
					// -> orderBy('n.create_at','desc')
					->paginate(20);
		
		}
		
		return view( 'news.list',[ 'news'=>$news,'request'=>$keyword,'category_id'=>$category_id ] );
    }

	
	
	// 用于 资讯 编辑
	// 用于 栏目 编辑
	// 获取 资讯 的所有分类层级
	public static function getPath( $category_id='' ){
		// 分类信息
		$category_info = DB::table('category')
					->where( 'id','=',$category_id )
					->first();
		// 拼一个完整的path
		$category_info->path .=$category_id;
		// 转换成数组
		$category_arr=explode( '-',$category_info->path );
		// 清除无效值
		unset( $category_arr[0] );	
		$arr = array();
		foreach( $category_arr as $key=>$category_id )
		{
			$category_info = DB::table('category')->where( 'id','=',$category_id )->first();
			// 分类的 id 与 分类名
			$arr[$key]['category_name'] = $category_info->name;
			$arr[$key]['id'] = $category_info->id;
		}
		return $arr;
	}
	
	
	// 获取 资讯图片表 所有内容
    public static function getNewsPicById( $id )
	{
		// 图片表内容
		$pic_info = DB::table( 'news_pic as np' )
					-> where( 'np.news_id','=',$id )
					-> get();
		return $pic_info;
		
	}
	
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */

    // 资讯 创建 编辑 页面
    public function create($news_id='')
    {
        // 开始
        // 获取路由
        $route_array = request()->route()->getAction();
        $controller = explode("\\",$route_array['controller']);
        $result = explode("@",$controller[3]);
        // 控制器 	$result[0];
        // 方法 	$result[1];
        $auth_final = '';
        foreach( Session::get('auths') as $key=> $auth_info )
        {
            // 符合条件
            if( $auth_info['controller']==$result[0] && $auth_info['func']==$result[1] )
            {
                $auth_final = true;
                break;
            }else
            {
                $auth_final = false;
            }
        }
        // 权限验证失败
        if( !$auth_final )
        {
            return redirect('/')->with( ['authinfo'=>'没有此项权限'] );
        }
        // 结尾
		// 获取 一级分类 足球资讯
		$category = DB::table('category as c') 
						// 足球资讯
						-> where('c.id','=',1 ) 
						-> first();
		if( $news_id=='' )
		{
			// 创建
			return view( 'news.add', [ 'category'=>$category,'title' => '资讯添加'] );
		}else
		{
		
			// 编辑
			$news_info = DB::table('news')
								-> where('id', $news_id)
								-> first();
			
			// 线上
			$str = str_replace("/images",config('app.imgPath')."/images",$news_info->content);
			$news_info->content = $str;
			
			// 获取标签
			$tags_info = DB::table('tag_record as tr')
								-> select('t.name')
								-> leftJoin( 'tag as t','t.id','=','tr.tag_id' )
								-> where('tr.type',1)
								-> where('tr.record_id', $news_id)
								-> get();
			$tag_str = '';
			foreach( $tags_info as $key => $tag_name )
			{
				$tag_str .= $tag_name->name.',';
			}
			$tag_str = rtrim($tag_str,',');
			
			// 资讯 栏目 内容
			$category_path = $this::getPath( $news_info->category_id );
			return view( 'news.add', [ 'category'=>$category,'title' => '资讯修改', 'news_info'=>$news_info,'category_path'=>$category_path,'tag_str'=>$tag_str ] );
		}
		
    }

    // 执行 资讯 创建 编辑
    public function store( $news_id='',Request $request )
    {
		$data = $request -> only('category','title','Sectitle','keywords','tags','from','content');
		
		if( empty($data['tags']) )
		{
			$this->show_msg( '请输入标签' );
		}
		// 中文替换 ,
		$data['tags'] = str_replace("，",",",$data['tags']);
		// 页面传来的标签内容
		$tag_arr = explode( ',',$data['tags'] );
		unset($data['tags']);
		// 存放标签id
		$tagIdArr = array();
		foreach( $tag_arr as $key => $tag )
		{
			// 检测标签库 是否已存在
			$history = DB::table('tag')
					-> where('name',$tag)
					-> first();
			// 不存在
			if( empty($history) )
			{
				// 执行插入 并获取标签id
				$tagIdArr[$key] = DB::table('tag')->insertGetId( ['name'=>$tag] );
			}else
			{
				// 获取现有的标签id
				$tagIdArr[$key] = $history->id;
			}
		}
		
		
		// 验证 
		// 清除无效值
		unset($data['category'][0]);
		// 包含 -1 
		if( in_array( '-1',$data['category'] ) )
		{
			$this -> show_msg( '请将分类补充完整' );
		}
		foreach( $data['category'] as $key => $category_id )
		{
			// 最后一次为 父类id
			$data['category_id'] = $category_id;
		}
		unset( $data['category'] );
		
		$title_length=mb_strlen( $data['title'],'utf-8' );
		if( $title_length<1 ){
			$this->show_msg('请输入标题');
		}
		
		if( empty($data['Sectitle']) ){
			$data['Sectitle']='';
		}
		if( empty($data['keywords']) ){
			$data['keywords']='';
		}

	
		if( empty($data['from']) ){
			$data['from']='';
		}
		if( empty($data['content']) ){
			$this->show_msg( '请输入资讯内容' );
		}
		
		// 正则 匹配图片地址
		$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
		// 检查百度编辑器里的配置图片显示地址 与 app.imgPath 是否一致 必须一致
		// 线上
		$data['content'] = str_replace( config('app.imgPath'),'',$data['content'] );
		preg_match_all($pattern,$data['content'],$pics);
		$pics=$pics[1];
		if( count($pics) < 1 )
		{
			$this->show_msg('请上传资讯图片');
		}
		
		if( $news_id == '' )
		{
			// 创建
			// 3审核通过
			$data['status']=3;
			$data['admin_id']=Session::get('admin_id');
			$data['create_at']=date('Y-m-d H:i:s',time());
			
			// 1. 主表
			$insert_id = DB::table('news')->insertGetId( $data );
			if( !$insert_id )
			{
				$this->show_msg( '添加主表失败' );
			}
			
			// 遍历 标签 关联 资讯
			foreach( $tagIdArr as $key => $tag_id )
			{
				$tag_record_arr = array();
				// 资讯 标签
				$tag_record_arr['type'] = 1;
				$tag_record_arr['tag_id'] = $tag_id;
				$tag_record_arr['record_id'] = $insert_id;
				DB::table('tag_record')->insertGetId( $tag_record_arr );
			
			}
			
			
			// 遍历 图片 地址信息
			foreach( $pics as $key => $file_path )
			{
				
				$pic = array();
				if($key==0)
				{
					// 封面
					$pic['status'] = 1;
				}
				$pic['news_id'] = $insert_id;
				$pic['pic_url'] = $file_path;
				// 3. 图片表
				DB::table('news_pic')->insertGetId($pic);
			}
			
			/*
			* 	写日志 
			* 	参数：$type		类型 1是资讯
			*		  $link_id	关联表的ID
			*		  $content	操作说明
			*/
			$this -> write_log(1,$insert_id,'添加资讯 ['.$insert_id."] ".$data['title']);
			$this->show_msg( '添加资讯成功' );
			
		}else
		{
			// 编辑 
			// 获取 现有旧表的 图片地址
			$now_pics = DB::table('news_pic')
							-> where( 'news_id','=',$news_id )
							-> get();
			$old = array();
			foreach( $now_pics as $k => $pic_info )
			{
				// 转成数组
				$old[ $pic_info->id ]=$pic_info->pic_url;
			}
			// 获取差集 结果为要删除的图片
			$del = array_diff($old,$pics);
			if( count($del)>0 )
			{
				foreach( $del as $pic_id => $pic_info )
				{
					// 线上
					$file = '../../image'.$pic_info;
					if( file_exists($file) )
					{
						// 删除 文件
						unlink( $file );	
					}
					// 删除 图片表旧数据
					$delete = DB::table('news_pic')
								-> where( 'id','=',$pic_id )
								-> delete();
					
				}
			}
			// 获取差集 为新增图片
			$new = array_diff( $pics,$old );
			
			foreach( $new as $key => $file_path )
			{
				$pic = array();
				if($key==0)
				{
					// 封面
					$pic['status'] = 1;
				}
				$pic['news_id'] = $news_id;
				$pic['pic_url'] = $file_path;
				// 2. 图片表
				DB::table('news_pic')->insertGetId($pic);
				
			}
			
			// 获取现有的标签
			$old_tag = DB::table('tag_record as tr')
				// 标签id
				-> select('t.id as tag_id','tr.id as trid')
				-> leftJoin('tag as t','t.id','=','tr.tag_id')
				-> where( 'tr.record_id','=',$news_id )
				-> where( 'tr.type','=',1 )
				-> get();
			$oldTagArr = array();
			foreach( $old_tag as $key=>$tagInfo )
			{
				$oldTagArr[$tagInfo->trid] = $tagInfo->tag_id;
			}
			// 要删的标签
			$tagDelDiff = array_diff( $oldTagArr,$tagIdArr );
			// 要添加的标签
			$tagAddDiff = array_diff( $tagIdArr,$oldTagArr );
			
			if( count($tagDelDiff)>0 )
			{
				foreach( $tagDelDiff as $trId=> $tag_id)
				{
					// 执行删除记录
					DB::table('tag_record')
						-> where( 'id','=',$trId )
						-> delete();
				}
				
			}
			
			if( count($tagAddDiff)>0 )
			{
				foreach( $tagAddDiff as $key=> $tag_id )
				{
					$tag_record_edit_arr = array();
					// 资讯 标签
					$tag_record_edit_arr['type'] = 1;
					$tag_record_edit_arr['tag_id'] = $tag_id;
					$tag_record_edit_arr['record_id'] = $news_id;
					DB::table('tag_record')->insertGetId( $tag_record_edit_arr );
				}
			}
			
			
			// 3. 主表数据
			$upd_res = DB::table('news')
							-> where( 'id','=',$news_id )
							-> update( $data );
			if( $upd_res )
			{
				$this -> write_log(1,$news_id,'编辑资讯 ['.$news_id."] ".$data['title']);
			}
			
			$this -> show_msg( '资讯编辑成功' );
				
			
		}
		
    }   
	
	
	// 执行 修改资讯 状态
	public function upStatus( $news_id,Request $request )
	{
		// 包含状态
		$data = $request -> except('_token');
        $res = DB::table('news')
					-> where('id',$news_id)
					-> update( $data );
		if($res)
		{
			// 修改成功
			$this -> show_msg('操作成功');
		}else
		{
			$this -> show_msg('操作失败');
		}
	}
	
	// 批量删除资讯
	public function delAll( Request $request )
	{
		// 包含资讯id
		$data = $request -> except('_token');
		// 清除无效值
		unset($data['all'][0]);	
		foreach( $data['all'] as $news_id )
		{
			// 获取 现有旧表的 图片地址
			$now_pics = DB::table('news_pic')
							-> where( 'news_id','=',$news_id )
							-> get();
			foreach( $now_pics as $pic_id => $pic_info )
			{
				// 线上
				$file = "../../image".$pic_info->pic_url;
				if( file_exists($file) )
				{
					// 删除 文件
					unlink( $file );	
				}
			}
		
		}
		// 2.从表
		$news_pic = DB::table('news_pic')
					-> whereIn( 'news_id',$data['all'] )
					-> delete();
		
		// 1.主表
		$news = DB::table('news')
				-> whereIn( 'id',$data['all'] )
				-> delete();
		if( $news )
		{
			$this -> show_msg('删除成功');
		}
		$this -> show_msg('删除失败');
		
	
	}
	
	
	// 添加 编辑 资讯图片 属性页面
	public function addalt( $news_id='' )
	{
		// 图片表 所有内容
		$pic_info = $this::getNewsPicById( $news_id );
		$new = array();
		foreach( $pic_info as $key => $array )
		{
			$new[$key]['id']=$array->id;
			$new[$key]['news_id']=$array->news_id;;
			
			// 线上
			$str = str_replace("/images",config('app.imgPath')."/images",$array->pic_url);
			$new[$key]['pic_url']=$str;
			$new[$key]['alt']=$array->alt;
			$new[$key]['status']=$array->status;
		}
		$pic_info = '';
		$pic_info = $new;
		// 创建
		return view( 'news.alt', [ 'title' => '图片alt属性添加' , 'pic_info'=>$pic_info,'news_id'=>$news_id ] );
	
	}
	
	
	// 执行 修改 图片 属性
	public function updalt( $news_id='',Request $request)
	{
		
		$data = $request -> except('_token');
		if( !isset($data['face']) )
		{
			$this -> show_msg('请选择封面');
		}
		
		// 根据 资讯ID
		// 全部设为 不是封面
		DB::table('news_pic')
					-> where( 'news_id','=',$news_id )
					-> update( ['status'=>2] );
							
		DB::table('news_pic')
					-> where( 'id','=',$data['face'] )
					// 设为封面
					-> update( ['status'=>1] );
		
		// 按,分割
		$alt_info = explode( ',',rtrim($data['alt'],',') );
		// 每个值包含着 图片ID 的 alt内容 3:这是图片内容
		foreach( $alt_info as $key => $alt_str )
		{
			// 按 : 分割
			$alt = explode( ':',$alt_str );
			// 图片ID
			$pic_id = $alt[0];
			$insert = array();
			// 图片alt内容
			$insert['alt'] = $alt[1];
			$upd_res = DB::table('news_pic')
							->where( 'id','=',$pic_id )
							->update( $insert );
		}
		$this -> show_msg('设置成功');
		
	}


}
